<?php
class DynamicRelationARObject extends lmbActiveRecord
{
  protected $_db_table_name = 'user_for_test';
  static $define_dynamic_relation = false;
  
  function _defineRelations()
  {
    parent :: _defineRelations();
    
    if (self :: $define_dynamic_relation)
    {
      $this->_hasOne('dynamic_relation', $has_one = array('field' => 'linked_object_id', 'class' => 'TestOneTableObject'));
    }
  }
}

class DynamicRelationByTableFieldARObject extends lmbActiveRecord
{
  protected $_db_table_name = 'user_for_test';
  
  static $table_field = 'some_not_existing_table_field';
  
  function _defineRelations()
  {
    parent :: _defineRelations();
    
    if ($this->has(self::$table_field))
    {
      $this->_hasOne('dynamic_relation', $has_one = array('field' => 'linked_object_id', 'class' => 'TestOneTableObject'));
    }
  }
}

class TestDefineRelationsDynamicly extends lmbARBaseTestCase
{
  protected function create_one_table_object()
  {
    $rel_obj = new TestOneTableObject();
    $rel_obj->set('content', 'content_'.rand(0, 1000));
    $rel_obj->save();
    return $rel_obj;
  }
  
  protected function create_user_for_test_obj($extender_class_name)
  {
    $obj = new $extender_class_name;
    $obj->setFirstName('User_' . rand(0, 1000));
    $obj->save();
    return $obj;
  }
  
  function testNegativeDefineDynamicRelation()
  {
    $obj = $this->create_user_for_test_obj('DynamicRelationARObject');
    
    try
    {
      $obj->get('dynamic_relation');
      $this->assertTrue(false);
    }
    catch (lmbNoSuchPropertyException $e)
    {
      $this->assertTrue(true);
    }
  }
  
  function testPositiveDefineDynamicRelation()
  {
    $rel_obj = $this->create_one_table_object();
    
    DynamicRelationARObject::$define_dynamic_relation = true;
    $obj = $this->create_user_for_test_obj('DynamicRelationARObject');
    $obj->set('dynamic_relation', $rel_obj);
    $obj->save();
    
    $this->assertEqual('TestOneTableObject', get_class($obj->get('dynamic_relation')));
  }
  
  function testNegativeDefineDynamicRelationByTableField()
  {
    $obj = $this->create_user_for_test_obj('DynamicRelationByTableFieldARObject');
    
    try
    {
      $obj->get('dynamic_relation');
      $this->assertTrue(false);
    }
    catch (lmbNoSuchPropertyException $e)
    {
      $this->assertTrue(true);
    }
  }
  
  function testPositiveDefineDynamicRelationByTableField()
  {
    $rel_obj = $this->create_one_table_object();
    
    DynamicRelationByTableFieldARObject :: $table_field = 'linked_object_id';
    
    $obj = $this->create_user_for_test_obj('DynamicRelationByTableFieldARObject');
    $obj->set('dynamic_relation', $rel_obj);
    $obj->save();
    
    $this->assertEqual('TestOneTableObject', get_class($obj->get('dynamic_relation')));
  }
}